package br.com.ac.fatureweb.utilitary.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("br.com.ac.fatureweb.utilitary.validator.EmailValidator")
public class EmailValidator implements Validator
{
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\."
			+ "[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*"
			+ "(\\.[A-Za-z]{2,})$";

	private final Pattern pattern;

	private Matcher matcher;

	private static final String ERROR_MESSAGE = "E-mail: Formato Inválido.";

	public EmailValidator()
	{
		pattern = Pattern.compile(EMAIL_PATTERN);
	}

	/*
	 * (non-Javadoc)
	 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(final FacesContext context, final UIComponent component,
			final Object value) throws ValidatorException
	{
		matcher = pattern.matcher(value.toString());
		if ( !matcher.matches() )
		{
			throw new ValidatorException(new FacesMessage(
					FacesMessage.SEVERITY_ERROR, ERROR_MESSAGE, null));
		}
	}
}